package com.atguigu.flink.chapter04_window.keyby;

import com.atguigu.flink.pojo.MyUtil;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;


public class Demo9_KeyByTimeSession
{
    public static void main(String[] args) {


       Configuration conf = new Configuration();
       conf.setInteger("rest.port", 3333);
       StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);


        env
           .socketTextStream("hadoop103", 8888)
           .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           })
           .keyBy(WaterSensor::getId)
           //一个3个元素大小(size)的滚动窗口
           .window(ProcessingTimeSessionWindows.withGap(Time.seconds(5)))
           .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>()
           {
               @Override
               public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                   MyUtil.printTimeWindow(context.window());
                   out.collect(MyUtil.toList(elements).toString());
               }
           }).setParallelism(1)
           .print();

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
    }
}
